<?php
include dirname(__FILE__) . '/../../config.php';
include dirname(__FILE__) . '/model.php';
include('simple_html_dom.php');

	function GetDateFromSql($i)
	{   
	    if ($i ==null) 
		{
			$query = "SELECT id FROM ng__kategorii ORDER BY id DESC Limit 0,1";
			$result = mysql_query($query) or die('Query failed: ' . mysql_error());
			$line = mysql_fetch_array($result, MYSQL_ASSOC);
			$i=$line['id'];
			$j=1;
		} else $j=$i;
		for ($j; $j<=$i; $j++)
		{
		    $query = "SELECT added_date FROM ng__novosti Where category_id={$j} ORDER BY added_date DESC Limit 0,1";
			$result = mysql_query($query) or die('Query failed: ' . mysql_error());
			$line = mysql_fetch_array($result, MYSQL_ASSOC);
			$res[]=array("added_date"  => $line['added_date']);
			//echo "addet date = ".$line['added_date']."<BR>";
		}
		unset($j,$i,$line['id'],$query,$result);//ggg
		return $res;	
	}

	function GetTableFromSql()
	{
		$query = "SELECT id,title FROM ng__kategorii";
		$result = mysql_query($query) or die('Query failed: ' . mysql_error());
		while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
		{
		 $mas[]=array( "id"    => $line['id'],
					   "title" => $line['title']);
		}
		unset($query,$result);
		return $mas;				
	}	

	function Dates($data)
	{
		$d=date_parse_from_format("D,d M Y H:i ", $data);
		$date="{$d['year']}-{$d['month']}-{$d['day']} {$d['hour']}:{$d['minute']}";
		unset($d,$data);
		return $date;
	}
	
	function DataFromMySql($date)
	{
		$zz=date_parse_from_format("Y-m-d H:i ", $date);
		$zz="{$zz['year']}-{$zz['month']}-{$zz['day']} {$zz['hour']}:{$zz['minute']}"; 
	}
	
		function UpdateMysqlTable($category_id,$date,$title,$stori_short,$stori_full,$see)
	{
		$category_id = mysql_real_escape_string($category_id);
		$date		 = mysql_real_escape_string($date);
		$title		 = mysql_real_escape_string($title);
		$stori_short = mysql_real_escape_string($stori_short);
		$stori_full  = mysql_real_escape_string($stori_full);
		$see		 = mysql_real_escape_string($see);
		$query = "insert into ng__novosti values('','{$category_id}','{$date}','{$title}','{$stori_short}','{$stori_full}','1')";
		$result = mysql_query($query) or die('Query failed: ' . mysql_error());
		unset($category_id,$date,$title,$stori_short,$stori_full,$see);
	}
	
	function MysqlSearh($title)
	{
	    //$title = substr_unicode($title, 0, 50);
	    $title = mysql_real_escape_string($title);
	    echo "title = {$title}<br>";
	    $query = "SELECT title FROM ng__novosti Where title='{$title}'";
		$result = mysql_query($query) or die('Query failed: ' . mysql_error());
		$line = mysql_fetch_array($result, MYSQL_ASSOC);
		unset($title,$query,$result);
		return $line['title'];
	}
	
	function substr_unicode($str, $s, $l = null) 
	{
      return join("", array_slice(preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
    }

	function GetNews($mas,$result,$mastab,$i)
	{		
		foreach ($result as $line)
		{

			$zz= $line['added_date'];
			$zz=strtotime($zz);
			if ($zz == null) $zz=0;

			$ch = curl_init( $mas[$mastab[$i]['title']]);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$content = curl_exec( $ch );

			 $rss= simplexml_load_string($content);
			 curl_close( $ch );
			foreach($rss->channel->item as $t)
			{			
				$date=Dates($t->pubDate);
				$date1=strtotime($date);

				if ( $date1 > $zz)
				{
					$category_id=$i+1;
					//$date;
					$title=$t->title;
					$stori_short=$t->description;
					$see=1;
					if (MysqlSearh($title) == null)
           				{
                          $stori_full=GetFullnews($t->link);						
						  UpdateMysqlTable($category_id,$date,$title,$stori_short,$stori_full,$see);
						}
					unset($category_id,$date,$title,$stori_short,$stori_full,$see,$date1);
				}
				else break;
				
			}
			unset($rss,$content,$ch,$zz);
			$i++;
		}
	}
	
	function GetFullnews($url)
	{
	    if ($html != null) {$html->clear();}
		unset($html);
	    set_time_limit(0);
		$html = file_get_html($url);
		foreach($html->find('div [id="article_body"]') as $element)
		{ 		
			return $element;

		}
		
	}

 $mas=array(  'Hi-tech'  => 'http://news.tut.by/rss/it.rss',
              'Наука'    => 'http://news.tut.by/rss/it/education.rss',
              'Спорт'    => 'http://news.tut.by/rss/sport.rss',
              'Авто'     => 'http://news.tut.by/rss/auto.rss',
              'Культура' => 'http://news.tut.by/rss/culture.rss'
			  );
$g=$_GET['id'];			  
if ($g == null) 
    { 
     $result=GetdatefromSql(null); 
	 $i=0;
    }else 
	    { 
	        $result=GetdatefromSql($g); 
	        $i=$g-1;
        }
		
$mastab=GetTableFromSql();
GetNews($mas,$result,$mastab,$i);
echo "<script>history.go(-1)</script>";
?>